package marcis.jarina.web.gui.entity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * This entity should takes care about paging.
 * <p/>
 * Author: Jan Marcis
 * Date: 27.2.11
 * Time: 22:25
 */
public class WrappedList<T> {

    public static int PER_PAGE = 10;

    private int pageNr;

    private List<T> decoratedList = new ArrayList<T>();

    /**
     * @param decoratedList As input there is a list comming from database.
     *                      This list length is already shortened by limits.
     */
    public WrappedList(Collection<T> decoratedList) {
        for(T t : decoratedList) {
            this.decoratedList.add(t);
        }
        refresh();
    }

    private void refresh() {
        int i;
        T entity;
        for (i = pageNr * PER_PAGE; i < (pageNr + 1) * PER_PAGE; i++) {
            try {
                entity = decoratedList.get(i);
            } catch (IndexOutOfBoundsException e) {
                break;
            }
            if (entity == null) {
                break;
            }
        }
    }


    public void setPageNr(int pageNr) {
        this.pageNr = pageNr;
    }

    public String getNextPage() {
        return String.valueOf(pageNr + 1);

        //TODO FIXME nejsem si jist jak zjistit
        /*
        if ((pageNr + 1) * PER_PAGE > decoratedList.size()) {
            return String.valueOf(pageNr);
        } else {
            return String.valueOf(pageNr + 1);
        }
        */
    }

    public String getPreviousPage() {
        return String.valueOf(pageNr - 1);
        //TODO FIXME nejsem si jist jak zjistit
        /*
        if (pageNr - 1 < 0) {
            return String.valueOf(pageNr);
        } else {
            return String.valueOf(pageNr - 1);
        }
        */
    }

    public List<T> getDecoratedList() {
        return decoratedList;
    }

    public static <T> WrappedList<T> getWrappedList(Collection<T> collection, int page) {
        if (collection != null && collection.size() > 0) {
            WrappedList<T> wrappedList = new WrappedList<T>(collection);
            wrappedList.setPageNr(page);
            return wrappedList;
        }
        return null;
    }
}
